<template>
  <div>
    <el-container>
      <el-main>
        <el-col :xs="24">
          <el-card header="申请管理">
            <el-autocomplete
              popper-class="my-autocomplete"
              v-model="state"
              :fetch-suggestions="querySearchAsync"
              placeholder="查找物品批次"
              @select="handleSelect">
              <template slot-scope="{ item }">
                <div class="name">{{ item.value }} </div>
                <span class="addr">{{ item.department }} </span>
                <span class="addr">{{ item.provider }}</span>
              </template>
            </el-autocomplete>
            <!---->
            <el-table :key="itemKey" ref="multipleTable" :data="tableData" :fit="true" :show-header="true">
              <el-table-column type="selection"></el-table-column>
              <el-table-column prop="no" label="id" sortable="true" v-if="false"></el-table-column>
              <el-table-column prop="id" label="序号"></el-table-column>
              <el-table-column prop="requisitionId" label="领用流水号"></el-table-column>
              <el-table-column prop="provider" label="供货单位"></el-table-column>
              <el-table-column prop="department" label="部门名称"></el-table-column>
              <el-table-column prop="status" label="状态"></el-table-column>
              <el-table-column prop="remark" label="备注"></el-table-column>
              <el-table-column fixed="right" width="250px">
                <template slot="header" slot-scope="scope">
                  <el-button
                    size="mini"
                    type="primary"
                    @click="handleInsert(scope.$index, scope.row)"

                  >添加</el-button>
                </template>
                <template slot-scope="scope">
                  <el-button
                    mc-type="column-el-button"
                    size="mini"
                    type="primary"
                    @click="handleEdit(scope.$index, scope.row)">修改</el-button>
                  <el-button mc-type="column-el-button" size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删 除</el-button>
                  <el-button
                    mc-type="column-el-button"
                    size="mini"
                    type="primary"
                    @click="handleStatus(scope.$index, scope.row)"
                    :disabled = ButtonVis >提交</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination style="margin-left: -5px;" layout="prev,pager,next" :total="pageTotal" :current-page.sync="currentPage"></el-pagination>
          </el-card>
        </el-col>
      </el-main>
    </el-container>
    <!--添加弹窗-->
    <el-dialog title="新建申请" :visible.sync="insFormVisible" :before-close="handleInsClose" width="40%">
      <el-form class="action-form" :model="insForm" label-width="100px">
        <el-form-item label="部门名称">
          <el-input v-model="insForm.insdepartment" :disabled="true"/>
        </el-form-item>
        <el-form-item label="供货单位">
          <el-input v-model="insForm.insprovider" />
        </el-form-item>
        <el-form-item label="验收流水号">
          <el-autocomplete
            popper-class="my-autocomplete"
            v-model= "insForm.AcceptId"
            :fetch-suggestions="querySearchAsync"
            placeholder="绑定流水号"
            @select="handleSelect">
            <template slot-scope="{ item }">
              <div class="name">{{ item.value }} </div>
              <span class="addr">{{ item.department }} </span>
              <span class="addr">{{ item.provider }}</span>
            </template>
          </el-autocomplete>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="insFormCancel()">取 消</el-button>
        <el-button type="primary" @click="insFormConfirm()">确 定</el-button>
      </div>
    </el-dialog>

    <!--编辑弹窗-->
    <el-dialog title="修改申请信息" :visible.sync="editFormVisible" :before-close="handleEditClose" width="40%">
      <el-form class="action-form" :model="updForm" label-width="100px">
        <el-form-item label="序号">
          <el-input :placeholder="updForm.id" :disabled="true" />
        </el-form-item>
        <el-form-item label="流水号">
          <el-input v-model="updForm.acceptId" :disabled="true" />
        </el-form-item>
        <el-form-item label="部门名称">
          <el-input v-model="updForm.department" :disabled="true"/>
        </el-form-item>
        <el-form-item label="供货单位">
          <el-input v-model="updForm.provider" :disabled="true"/>
        </el-form-item>
        <el-form-item label="填充">
          <el-input v-model="updForm.remark" :disabled="true"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updFormCancel()">取 消</el-button>
        <el-button type="primary" @click="updFormConfirm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { AddPurchase, selectAll, selectByAccId, selectByNot, RemoveAdmin,selectByOK, selectByYes, Select, selAccountDepart,
  editStatus } from '@/api/material-delivery/pur-admin'
import { selectById_good } from '@/api/material-delivery/purchase-plan'
export default {
  data() {
    return {
      search: '',
      searchDatas: [],//初始时搜索框预加载数据
      nameDatas: [], //新验收物品时预加载物品名称
      Data: [],       //所有验收完成的数据
      state: '',
      state1: '',
      timeout: null,
      tableData: [],//选中acceptid后table的加载数据
      itemKey: '',
      loading: false,
      editFormVisible: false,
      insFormVisible: false,
      ButtonVis: false,
      selectValue: '',
      status: '',
      AcceptId: '',
      account: this.$store.getters.name, // 获取用户信息
      acoDepartName: '',
      insForm: {
        insdepartment: '',
        insprovider: '',
        AcceptId: ''
      },
      updForm: {
        id: '',
        acceptId: '',
        department: '',
        provider: '',
        invoice: '',
        requisition_id: ''
      }
    }
  },
  headers: {
    Authorization: getToken()
  },
  mounted() {
    this.getDepartName()
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      selectByNot().then((response) => {
        this.searchDatas = response.data
      })
      selectByOK().then((response) => {
        this.Data = response.data
      })

    },
    handleSelect(item) {
      selectByAccId(item.value).then((response) => {
        this.selectValue = item.value
        //this.tableData = response.data
        this.AcceptId = item.value
        this.itemKey = Math.random()
      })
    },
    querySearchAsync(queryString, cb) {
      Select(this.insForm.insdepartment, this.insForm.insprovider).then((response) => {
        this.Data = response.data
        this.itemKey = Math.random()
      })
      var searchDatas = this.Data;
      var results = queryString ? searchDatas.filter(this.createStateFilter(queryString)) : searchDatas;
      var results1 = []
      for (let i = 0; i < results.length; i++) {
        if (results[i].department === this.acoDepartName) {
          results1.push({
            'value': results[i].acceptId,
            'department': results[i].department,
            'provider': results[i].provider
          })
        }
      }
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results1);
      }, 2000 * Math.random()) ;
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.acceptId.toLowerCase().indexOf(queryString.toLowerCase()) > -1);
      }
    },
    handleInsert(index, row) {
      this.insFormVisible = true
    },
    handleEditClose() {
      this.editFormVisible = false
      this.updForm.id = ''
      this.updForm.acceptId = ''
      this.updForm.department = ''
      this.updForm.provider = ''
      this.updForm.invoice = ''
      this.updForm.place = ''
      this.updForm.contract = ''
      this.updForm.status = ''
      this.updForm.createtime = ''
    },
    insFormConfirm() {
      if (this.insForm.insdepartment === '' || this.insForm.insprovider === '' || this.insForm.AcceptId === '') {
        this.$message.error('信息不能为空')
      } else {
        AddPurchase(this.insForm.insdepartment, this.insForm.insprovider, this.insForm.insinvoice, this.insForm.AcceptId).then(response => {
          this.$message.success(response.message)
          selectAll(this.acoDepartName).then((response) => {
            this.tableData = response.data
            //this.AcceptId = response.data[0].acceptId
          })
          this.insFormVisible = false
          this.loading = true
          this.insForm.insdepartment = ''
          this.insForm.insprovider = ''
          this.insForm.insinvoice = ''
          this.insForm.insplace = ''
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '已存在正在申请或者正在审批的领用申请'
          })
        })
      }
    },
    insFormCancel() {
      this.insFormVisible = false
      // this.insForm.insdepartment = ''
      this.insForm.insprovider = ''
      this.insForm.AcceptId = ''
    },
    handleEdit(index, row) {
      if (row.status === '申请完成') {
        this.$message({
          type: 'info',
          message: '提交过后无法再次修改'
        })
        return
      }
      this.editFormVisible = true

      this.updForm.id = row.id
      this.updForm.acceptId = row.requisitionId
      this.updForm.department = row.department
      this.updForm.provider = row.provider
      this.updForm.invoice = row.invoice
    },
    handleDelete(index, row) {
      this.$confirm('此操作将删除申请信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        RemoveAdmin(this.tableData[index].id).then((response) => {
          this.$message.success(response.message)
          selectAll(this.acoDepartName).then((response) => {
            this.tableData = response.data
            //this.AcceptId = response.data[0].acceptId
          })
          this.loading = true
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    updFormCancel() {
      this.editFormVisible = false

      this.updForm.id = ''
      this.updForm.acceptId = ''
      this.updForm.department = ''
      this.updForm.invoice = ''
      this.updForm.requisition_id = ''
      this.updForm.provider = ''
    },
    handleInsClose() {
      // this.insForm.insdepartment = ''
      this.insForm.insprovider = ''
      this.insForm.AcceptId = ''
      this.insFormVisible = false
    },
    // 获取部门名称
    getDepartName() {
      selAccountDepart(this.account).then((response) => {
        this.acoDepartName = response.data.departName
        console.log(this.acoDepartName)
        //debugger
        this.insForm.insdepartment = response.data.departName
        this.updForm.department = response.data.departName
        console.log('部门信息：' + response.data.departName)
        selectAll(this.acoDepartName).then((response) => {
          this.tableData = response.data
          this.AcceptId = response.data[0].acceptId
        })
      })
    },
    handleStatus(index, row) {
      if (row.status !== '申请中') {
        this.$message({
          type: 'info',
          message: '无法再次提交'
        })
        return
      }
      this.$confirm('请确认好物资添加已完成, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        editStatus(row.id, row.provider, this.AcceptId, row.department, row.requisitionId,
          '', '', '', '申请完成', '', '').then((response) => {
          this.$message.success(response.message)
          this.loading = true
        })
        console.log(this.acoDepartName)
        selectAll(this.acoDepartName).then((response) => {
          this.tableData = response.data
          this.loading = false
          this.itemKey = Math.random()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    }
  }
}
</script>

<style scoped>
  .my-autocomplete {
    line-height: normal;
    padding: 7px;
  }
  .name {
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .addr {
    font-size: 10px;
    color: #b4b4b4;
  }
  .highlighted .addr {
    color: #ddd;
  }

  .member-box-card {
    width: 95%;
    margin: 20px auto
  ;
  }
  #input-field {
    width: 200px;
    display: inline;
  }
  #member-table {
    margin-top: 5px;
  }
  .action-form {
    width: 400px;
  }
</style>
